package com.spzx.product.service.impl;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.annotation.Excel;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.bean.BeanUtils;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.product.domain.Category;
import com.spzx.product.domain.vo.CategoryExcelVO;
import com.spzx.product.mapper.CategoryMapper;
import com.spzx.product.service.CategoryService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Override
    public List<Category> treeSelect(Long id) {
        List<Category> categories = baseMapper.selectList(new LambdaQueryWrapper<Category>().eq(Category::getParentId, id));
//        baseMapper.selectCount(Wrappers.lambdaQuery(Category.class).eq(Category::getParentId,))
        categories.forEach((category)->{
            Long count = baseMapper.selectCount(Wrappers.lambdaQuery(Category.class).eq(Category::getParentId, category.getId()));
            if (count>0 && count!=null){
                category.setHasChildren(true);
            }else {
                category.setHasChildren(false);
            }
        });

        return categories;
    }

    @Override
    public void exportData(HttpServletResponse response) {
            //1.查询分类的所有信息
        List<Category> categories = baseMapper.selectList(null);
        List<CategoryExcelVO> categoryExcelVOS = new ArrayList<>(categories.size());
        //通过easyexcel写数据到excel文件 + 讲文件流写入到响应报文中
        for(Category category : categories) {
            CategoryExcelVO categoryExcelVo = new CategoryExcelVO();
            BeanUtils.copyProperties(category, categoryExcelVo);
            categoryExcelVOS.add(categoryExcelVo);
        }

        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");


            String fileName = URLEncoder.encode("分类数据", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");



            EasyExcel.write(response.getOutputStream())//将文件写入到响应报文中
                    .sheet("分类数据")//设置工作簿名称
                    .head(CategoryExcelVO.class)//excel文件的表头根据Category类来生成 将需要的的属性加上注解@Excel
                    .doWrite(categoryExcelVOS);//将要写的数据传入
        } catch (IOException e) {
            throw new ServiceException("文件导出异常");
        }


    }

    @Override
    public void importData(MultipartFile file) {
        try {
            List<CategoryExcelVO> list = EasyExcel.read(file.getInputStream()).head(CategoryExcelVO.class).sheet().doReadSync();
            if (!CollectionUtils.isEmpty(list)){
              List<Category> categoryList= new ArrayList<>();
                    list.forEach(categoryExcelVO -> {
                        Category category = new Category();
                        BeanUtils.copyProperties(categoryExcelVO,category);
                        categoryList.add(category);

                    });
                    this.saveBatch(categoryList);

            }



        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    @Override
    public List<Category> selectCatesTree() {
        //查找所有分类 然后将其子类组装进父类
        List<Category> categories = this.list();
        //挑选出一级分类集合
        List<Category> levelOneCates = categories.stream()
                .filter(category -> category.getParentId()==0)
                .collect(Collectors.toList());;
        buildCatesTree(categories,levelOneCates);

        return levelOneCates;
    }

    public void  buildCatesTree(List<Category> all , List<Category> parents){
//        先判断集合是为空
        if (CollectionUtils.isEmpty(all)||CollectionUtils.isEmpty(parents)){
            return;
        }
        parents.forEach(parent->{
            List<Category> childen = all.stream().filter(category -> category.getParentId().equals(parent.getId())).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(childen)){
                parent.setChildren(childen);
                // 将parent分类的下一级分类集合 当作父分类集合  再次查找他们的下一级
                buildCatesTree(all , childen);
            }


        });



    }


}
